package com.webchat.ugc.service.redpacket;


import com.webchat.common.constants.RedPacketConstants;
import com.webchat.common.exception.BusinessException;
import com.webchat.common.util.SpringContextUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 红包拆分实现方案服务工厂
 */
@Component
public class OpenRedPacketWithFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public static Map<String, AbstractOpenRedPacketService> services = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initServices();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void initServices() {

        services.put(RedPacketConstants.OpenRedPacketWithEnum.LUA.name(), applicationContext.getBean(OpenRedPacketWithLuaService.class));
        services.put(RedPacketConstants.OpenRedPacketWithEnum.LOCK.name(), applicationContext.getBean(OpenRedPacketWithRedissonLockService.class));
        services.put(RedPacketConstants.OpenRedPacketWithEnum.QUEUE.name(), applicationContext.getBean(OpenRedPacketWithQueueService.class));
    }

    public static AbstractOpenRedPacketService getService(String type) {
        AbstractOpenRedPacketService abstractOpenRedPacketService = services.get(type);
        if (abstractOpenRedPacketService == null) {
            throw new BusinessException("不支持的红包拆分服务");
        }
        return abstractOpenRedPacketService;
    }
}
